package com.frank.demo.service;/*
 *@author:xec
 *@date:2022/2/28  8:50
 */

import com.frank.demo.domain.Category;
import com.frank.demo.domain.CategoryExample;
import com.frank.demo.mapper.CategoryMapper;
import com.frank.demo.req.CategoryQueryReq;
import com.frank.demo.req.CategorySaveReq;
import com.frank.demo.resp.CategoryQueryResp;
import com.frank.demo.resp.PageResp;
import com.frank.demo.utils.CopyUtil;
import com.frank.demo.utils.SnowFlake;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CategoryService {

    @Resource
    private CategoryMapper categoryMapper ;

    @Resource
    private SnowFlake snowFlake;

    public List<CategoryQueryResp> getAll(){
        CategoryExample categoryExample = new CategoryExample();
        categoryExample.setOrderByClause("sort asc");
        List<Category> categoryList = categoryMapper.selectByExample(categoryExample);
        List<CategoryQueryResp> respList = CopyUtil.copyList(categoryList,CategoryQueryResp.class);
        return respList;
    }

    public PageResp<CategoryQueryResp> getCategory(CategoryQueryReq categoryQueryReq){
        CategoryExample categoryExample = new CategoryExample();
        CategoryExample.Criteria criteria = categoryExample.createCriteria();

        // 需要注意的是，这行代码只对遇到的第一个select查询有用，因此在使用时，想对那个select分页就写在它的上一行
        PageHelper.startPage(categoryQueryReq.getPage(), categoryQueryReq.getSize());// 1代码从第几页查，3代表每页显示3条数据.
        List<Category> categorys = categoryMapper.selectByExample(categoryExample);
        // 这里查出来的是Category，里面字段和表字段是一样的，但是我们返回出去的是响应封装类，因此要转化一下

        List<CategoryQueryResp> respList = CopyUtil.copyList(categorys,CategoryQueryResp.class);
        PageInfo<Object> pageInfo = new PageInfo<>();
        PageResp pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(respList);
        return pageResp;
    }

    /**
     * 更新和添加方法
     */
    public void save(CategorySaveReq req) {
        Category category = CopyUtil.copy(req, Category.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            category.setId(snowFlake.nextId());
            categoryMapper.insert(category);
        } else {
            // 更新
            categoryMapper.updateByPrimaryKey(category);
        }
    }


    public void delete(Long id) {
        categoryMapper.deleteByPrimaryKey(id);
    }
}
